package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var jwtAccessSecret []byte
var jwtRefreshSecret []byte
var accessExpireDuration time.Duration
var refreshExpireDuration time.Duration

// InitJWT 初始化JWT配置
func InitJWT(accessSecret, refreshSecret string, accessExpire, refreshExpire int) {
	jwtAccessSecret = []byte(accessSecret)
	jwtRefreshSecret = []byte(refreshSecret)
	accessExpireDuration = time.Duration(accessExpire) * time.Second
	refreshExpireDuration = time.Duration(refreshExpire) * time.Second
}

type Claims struct {
	UserID uint   `json:"userId"`
	Type   string `json:"type"` // "access" 或 "refresh"
	jwt.RegisteredClaims
}

// GenerateToken 生成 Access Token
func GenerateToken(userID uint) (string, error) {
	claims := Claims{
		UserID: userID,
		Type:   "access",
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(accessExpireDuration)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtAccessSecret)
}

// GenerateRefreshToken 生成 Refresh Token
func GenerateRefreshToken(userID uint) (string, error) {
	claims := Claims{
		UserID: userID,
		Type:   "refresh",
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(refreshExpireDuration)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtRefreshSecret)
}

// ParseToken 解析 Access Token
func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtAccessSecret, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		if claims.Type != "access" {
			return nil, errors.New("无效的Token类型")
		}
		return claims, nil
	}

	return nil, errors.New("无效的Token")
}

// ParseRefreshToken 解析 Refresh Token
func ParseRefreshToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtRefreshSecret, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		if claims.Type != "refresh" {
			return nil, errors.New("无效的Token类型")
		}
		return claims, nil
	}

	return nil, errors.New("无效的RefreshToken")
}
